package cn.iot.netty.service;

import cn.iot.common.dto.ResultMsg;
import cn.iot.common.utils.RedisUtils;
import cn.iot.netty.util.ElectricityMeterUtil;
import cn.iot.netty.util.InstructConstant;
import cn.iot.netty.util.InstructTypeConstant;
import cn.iot.netty.NettyServerHandler;
import cn.iot.sys.dao.*;
import cn.iot.sys.entity.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.util.*;

@Service("sendInstructsService")
public class SendInstructsServiceImpl implements SendInstructsService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private RedisUtils redisUtils;
    @Autowired
    private SysGatewayDao iotGatewayDao;
    @Autowired
    private SysDictDetailDao sysDictDetailDao;
    @Resource
    private SysEwDeviceDao sysEwDeviceDao;
    @Resource
    private SysEwdevicelogDao sysEwdevicelogDao;
    @Resource
    private SysGatewayDao sysGatewayDao;
    @Autowired
    private NettyServerHandler nettyServerHandler;
    @Resource
    private SysElectricityUseDao sysElectricityUseDao;


    @Override
    public ResultMsg operationElectricity(String operationType, Integer id) {
        //id设备id
        SysEwDevice sysEwDevice = sysEwDeviceDao.selectById(id);
        if (sysEwDevice == null) {
            throw new RuntimeException("不存在该设备");
        }

        Integer gatewayId = Integer.valueOf(sysEwDevice.getGatewayId());
        SysGateway sysGateway = sysGatewayDao.selectById(gatewayId);
        if (sysGateway == null) {
            throw new RuntimeException("该设备没有任何网关关联它");
        }
//        String deviceCode = sysGateway.getGatewayNo();
        String deviceCode = sysEwDevice.getDeviceCode();
        //拿到处理后的设备编号
        String address = ElectricityMeterUtil.deviceAddressConvert(deviceCode);
        String ip = "/"+sysGateway.getGatewayIp()+":"+sysGateway.getPort();
        //获取发送指令  (是拉闸  还是合闸  还是…………)
        //FE FE 68 00 00 00 95 02 04
        String instruce =getInstruce(address,operationType);

        if (instruce==null) {
            throw new RuntimeException("获取操作指令失败");
        }

        // 获取Netty服务器的ChannelGroup（所有客户端连接的集合）
        ChannelGroup channelGroup = nettyServerHandler.getChannelGroup();

        // 遍历所有连接的客户端
        Iterator channelIterator = channelGroup.iterator();
        while (channelIterator.hasNext()) {
            // 获取当前客户端的Channel对象
            Channel channel = (Channel) channelIterator.next();

            // 获取客户端的远程IP地址
            InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();

            // 比较客户端IP和目标网关的IP，如果相同，则发送控制指令
            if (ip.equals(insocket.toString())) {
                // 向该客户端Channel写入并刷新操作指令，发送控制命令
                channel.writeAndFlush(instruce);
                channel.flush();
                redisUtils.set(deviceCode, operationType);
            }
        }
        InstructTypeConstant byKey = InstructTypeConstant.getByKey(operationType);
        SysEwdevicelog sysEwdevicelog = new SysEwdevicelog();
        sysEwdevicelog.setDeviceCode(String.valueOf(id));
        sysEwdevicelog.setOperationIp(ip);
        sysEwdevicelog.setOperationContext(instruce);
        sysEwdevicelog.setOperationType(byKey.getValue());
        sysEwdevicelog.setOperationUser("admin");
        sysEwdevicelog.setCreateTime(new Date());
        sysEwdevicelogDao.insert(sysEwdevicelog);
        return new ResultMsg(200, "success", null);
    }

    public String getInstruce(String address, String operationType) {
        if (operationType.equals(InstructTypeConstant.E_MAIN_GATE_NO.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_ON_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_MAIN_GATE_OFF.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_PULL_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_A_GATE_OFF.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_A_PULL_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_A_GATE_NO.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_A_NO_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_B_GATE_OFF.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_B_PULL_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_B_GATE_NO.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_B_NO_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_MAIN_PARSM_INFO.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_METER_SUMMARY_INFO_INSTRUCT);
        } else if (operationType.equals(InstructTypeConstant.E_BALANCE_SETUPA.getKey())) {
            return ElectricityMeterUtil.getCompleteInstruct(address, InstructConstant.ELECTRICITY_BALANCE);
        }
        return null;
    }

    @Override
    public void callbackInstructResultMsg(String ip, String returnStr) {
        if(StringUtils.isEmpty(returnStr) || !returnStr.startsWith("FE")){
            return;
        }
        //获取回调设备编号
        String notFEStr = returnStr.substring(returnStr.indexOf("68")+2);
        String deviceType = notFEStr.startsWith("10")?"w":"e";
        //根据设备号找到数据，并更新数据
        if("e".equals(deviceType)){
            String addressNo = notFEStr.substring(0,notFEStr.indexOf("68"));
            //获取设备号
            String deviceNo = ElectricityMeterUtil.addressConvertNo(addressNo,true);
            String operationType = redisUtils.get(deviceNo);
            //删除redis中的数据
            redisUtils.delete(deviceNo);
            //电表操作
            handleOperation(deviceNo,operationType,notFEStr);
        }
        else{
            //水表操作
            String deviceCode = handleWaterOperation(notFEStr);
            //删除redis中的数据
            redisUtils.delete(deviceCode);
        }

    }

    /**
     * 处理水表返回操作
     * @param notFEStr 返回指令内容
     */
    private String handleWaterOperation(String notFEStr){
        String deviceNo = "";
        LambdaQueryWrapper<SysEwDevice> wrapper = new LambdaQueryWrapper<>();
        SysEwDevice vo = new SysEwDevice();
        if(notFEStr.indexOf("A0170000")>=0){
            //开阀成功
            //设备号
            deviceNo = notFEStr.substring(2,notFEStr.indexOf("AA05"));
            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo,true);
            vo.setSluiceStatus("1");

        }
        if(notFEStr.indexOf("A0170001")>=0){
            //关阀成功
            deviceNo = notFEStr.substring(2,notFEStr.indexOf("AA05"));
            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo,true);
            vo.setSluiceStatus("0");
        }
        if(notFEStr.indexOf("901F00")>=0) {
            deviceNo = notFEStr.substring(2,notFEStr.indexOf("8116901F"));
            deviceNo = ElectricityMeterUtil.addressConvertNo(deviceNo,true);
            //查询水表
            String data = notFEStr.substring(notFEStr.indexOf("901F00")+6,notFEStr.indexOf("901F")+14);
            String dataStr  = ElectricityMeterUtil.addressConvertNo(data,true);
            BigDecimal currWaterCount = new BigDecimal(dataStr).multiply(new BigDecimal("0.01"));
            logger.info("water info {}" , currWaterCount);
            handleWaterMater(deviceNo,  vo, currWaterCount);

        }
        wrapper.eq(SysEwDevice::getDeviceCode,deviceNo);
        sysEwDeviceDao.update(vo,wrapper);
        return deviceNo;

    }

    /**
     * 处理水表抄表信息
     * @param deviceNo
     * @param vo
     * @param currWaterCount
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleWaterMater(String deviceNo, SysEwDevice vo, BigDecimal currWaterCount) {
        //查询设备当前信息
        LambdaQueryWrapper<SysEwDevice> iotwrapper = new LambdaQueryWrapper<>();
        iotwrapper.eq(SysEwDevice::getDeviceCode, deviceNo);
        SysEwDevice devicevo = sysEwDeviceDao.selectOne(iotwrapper);
        //抄表前当前的水表总量
        BigDecimal currWaterTotle  = devicevo.getTotle()==null?BigDecimal.ZERO: devicevo.getTotle();
        //当前余额
        BigDecimal currBalance = devicevo.getDeviceBalance()==null?BigDecimal.ZERO: devicevo.getDeviceBalance();
        //当前剩余量
        BigDecimal currSurplus = devicevo.getDeviceSurplus()==null?BigDecimal.ZERO: devicevo.getDeviceSurplus();
        //当前水的使用量
        BigDecimal useQuantity = currWaterCount.subtract(currWaterTotle);

        LambdaQueryWrapper<SysDictDetail> dictWrapper = new LambdaQueryWrapper<>();
        dictWrapper.eq(SysDictDetail::getDictType,"commodity_unit_price");
        dictWrapper.eq(SysDictDetail::getDictLabel,"water") ;
        //查询单价 计算出使用水的费用 使用量*水费单价
        SysDictDetail dictDetail = sysDictDetailDao.selectOne(dictWrapper);
        BigDecimal useAmount = useQuantity.multiply(new BigDecimal(dictDetail.getDictValue()));
        //计算余额
        BigDecimal newBalance = currBalance.subtract(useAmount);
        if(currBalance.compareTo(BigDecimal.ZERO)<0){
            newBalance = currBalance.add(useAmount);
        }
        //计算剩余量
        BigDecimal newSurplus =  currSurplus.subtract(useQuantity);
        if(currSurplus.compareTo(BigDecimal.ZERO)<0){
            newSurplus = currSurplus.add(useQuantity);
        }

        //更新水表的余额，剩余量，总量
        vo.setDeviceBalance(newBalance);
        vo.setDeviceSurplus(newSurplus);
        vo.setTotle(currWaterCount);

        //记录抄水表的记录
        SysWaterUse billWaterUse = new SysWaterUse();
        billWaterUse.setDeviceId(devicevo.getId());
        billWaterUse.setUseCost(useAmount);
        billWaterUse.setBeforUseBalance(currBalance);
        billWaterUse.setUseWater(useQuantity);
        billWaterUse.setBeforUseWater(currSurplus);
//        billWaterUseDao.insert(billWaterUse);

        //执行指令前删除redis中的数据
        redisUtils.delete(deviceNo);
        if(newBalance.compareTo(BigDecimal.ZERO)<0 || newSurplus.compareTo(BigDecimal.ZERO)<0){
            //关闸
            operationElectricity("101",vo.getId());
            logger.info("{} Arrears closed",deviceNo);
        }else {
            //开闸
            operationElectricity("100",vo.getId());
            logger.info("{} Pay to open ",deviceNo);
        }
        logger.info("End of water meter reading");
    }

    /**
     * 电表处理操作类型，对不同的类型更新对应设备的信息
     * @param deviceNo
     * @param type
     */
    private void handleOperation(String deviceNo,String type,String notFEStr){
        LambdaQueryWrapper<SysEwDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysEwDevice::getGatewayId,deviceNo);
        SysEwDevice vo = new SysEwDevice();
        //合总电闸，拉闸或合闸后修改设备表状态
        if(InstructTypeConstant.E_MAIN_GATE_NO.getKey().equals(type)){
            vo.setElectricityStatus("1");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //拉总电闸
        if(InstructTypeConstant.E_MAIN_GATE_OFF.getKey().equals(type)){
            vo.setElectricityStatus("0");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //合A路电闸
        if(InstructTypeConstant.E_A_GATE_NO.getKey().equals(type)){
            vo.setElectricityAStatus("1");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //拉A路电闸
        if(InstructTypeConstant.E_A_GATE_OFF.getKey().equals(type)){
            vo.setElectricityAStatus("0");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //合B路电闸
        if(InstructTypeConstant.E_B_GATE_NO.getKey().equals(type)){
            vo.setElectricityBStatus("1");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //拉B路电闸
        if(InstructTypeConstant.E_B_GATE_OFF.getKey().equals(type)){
            vo.setElectricityBStatus("0");
            sysEwDeviceDao.update(vo,wrapper);
        }
        //获取电表参数信息
        if(InstructTypeConstant.E_MAIN_PARSM_INFO.getKey().equals(type)){
            getElectricityParamInfo(notFEStr,deviceNo);
        }
        //获取电表费控数据
        if(InstructTypeConstant.E_BALANCE_SETUPA.getKey().equals(type)){
            getElectricityBalanceInfo(notFEStr,deviceNo);
        }

    }


    /**
     * 定时任务抄表，回调此方法
     * @param notFEStr
     * @param deviceCode
     */
    @Transactional(rollbackFor = Exception.class)
    public void getElectricityBalanceInfo(String notFEStr,String deviceCode){
        String dataStr = notFEStr.substring(notFEStr.indexOf("81104A1C")+8,notFEStr.length()-4);
        //购买次数
        String payCount = dataStr.substring(0,4);
        String payCountStr = dataChange(payCount,0);
        logger.info("getElectricityBalanceInfo payCount {} {}",payCount,payCountStr);
        //最近购电金额
        String lastPayAmount = dataStr.substring(4,12);
        String lastPayAmountStr = dataChange(lastPayAmount,0);
        logger.info("getElectricityBalanceInfo lastPayAmount {} {}",lastPayAmount,lastPayAmountStr);
        //剩余金额
        String surplusAmount = dataStr.substring(12,20);
        surplusAmount = ElectricityMeterUtil.deviceAddressConvert(surplusAmount);
        surplusAmount = ElectricityMeterUtil.dataAreaSubtract33(surplusAmount);
        logger.info("getElectricityBalanceInfo surplusAmount {} {}",surplusAmount);
        int amount = Integer.parseInt(surplusAmount.replaceAll(" ",""),16);
        logger.info("getElectricityBalanceInfo amount {} {}",amount);
        String surplusAmountStr = String.valueOf(amount*0.01);
        logger.info("getElectricityBalanceInfo surplusAmount {} {}",surplusAmount,surplusAmountStr);
        //累计金额
        String sumAmount = dataStr.substring(20,28);
        String sumAmountStr = dataChange(sumAmount,0);
        logger.info("getElectricityBalanceInfo surplusAmount {} {}",sumAmount,sumAmountStr);

        //查询设备信息
        LambdaQueryWrapper<SysEwDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysEwDevice::getDeviceCode,deviceCode);
        SysEwDevice vo = sysEwDeviceDao.selectOne(wrapper);
        BigDecimal deviceBalance = vo.getDeviceBalance();
        BigDecimal deviceSurplus = vo.getDeviceSurplus();
        //当前电表总金额减去剩余金额，得出支付金额
        BigDecimal balanceDifference = new BigDecimal(sumAmountStr).subtract(new BigDecimal(surplusAmountStr));

        LambdaQueryWrapper<SysDictDetail> dictWrapper = new LambdaQueryWrapper<>();
        dictWrapper.eq(SysDictDetail::getDictType,"commodity_unit_price");
        dictWrapper.eq(SysDictDetail::getDictLabel,"electric") ;
        //查询单价
        SysDictDetail dictDetail = sysDictDetailDao.selectOne(dictWrapper);
        //计算出使用的电量-向下取整
        BigDecimal quantity = balanceDifference.multiply(new BigDecimal(dictDetail.getDictValue())).setScale(1,BigDecimal.ROUND_DOWN);
        //计算使用费用
        BigDecimal useBalance = deviceBalance.subtract(new BigDecimal(surplusAmountStr));
        logger.info("Electricity balance: {}",useBalance);
        //计算使用量
        BigDecimal useSurplus = useBalance.divide(new BigDecimal(dictDetail.getDictValue()));
        //计算设备剩余费用
        BigDecimal remnantBalance = deviceBalance.subtract(useBalance);
        BigDecimal remnantQuantity = deviceSurplus.subtract(useSurplus);
        SysElectricityUse billElectricityUse = new SysElectricityUse();
        billElectricityUse.setDeviceId(vo.getId());
        billElectricityUse.setBeforUseBalance(deviceBalance);
        billElectricityUse.setBeforUseWater(deviceSurplus);
        //账户余额与电表余额对比
        if(deviceBalance.compareTo(new BigDecimal(surplusAmountStr))>0){
            //使用过电，修改余额和可使用量
            vo.setDeviceBalance(remnantBalance);
            vo.setDeviceSurplus(remnantQuantity);
            //更新设备金额
            sysEwDeviceDao.updateById(vo);

            //添加抄表记录
//            billElectricityUse.setBeforUseWater(useSurplus);
            billElectricityUse.setUseWater(quantity);
            billElectricityUse.setUseCost(useBalance);
            billElectricityUse.setCreateTime(new Date());
            sysElectricityUseDao.insert(billElectricityUse);
        }else{
            //没有使用过电 添加抄表记录
            billElectricityUse.setBeforUseWater(deviceBalance);
            billElectricityUse.setUseCost(BigDecimal.ZERO);
            billElectricityUse.setUseWater(BigDecimal.valueOf(0));
            billElectricityUse.setCreateTime(new Date());
            sysElectricityUseDao.insert(billElectricityUse);
        }

        //结算余额小于0，拉闸停电
//        if(deviceBalance.compareTo(BigDecimal.ZERO)<0 || remnantBalance.compareTo(BigDecimal.ZERO)<0){
//            logger.info("Electricity Balance Not enough");
//            //获取发送指令
//            operationElectricity("2",vo.getId());
//            logger.info("Electricity Balance sendInstructs success");
//            //修改总闸状态
//            vo.setElectricityStatus("0");
//            sysEwDeviceDao.updateById(vo);
//        }else{
//            //余额大于0，合闸送电
//            logger.info("Electricity Balance enough");
//            operationElectricity("1",vo.getId());
//            logger.info("Electricity Balance sendInstructs success");
//            //修改总闸状态
//            vo.setElectricityStatus("1");
//            sysEwDeviceDao.updateById(vo);
//        }
    }

    /**
     * 获取电表参数信息
     * @param str
     */
    private void getElectricityParamInfo(String str,String deviceCode){
        //获取数据
        String datastr = str.substring(str.indexOf("B3E9")+4,str.length()-4);
        String dataBCD = ElectricityMeterUtil.hexAddcharacter(datastr," ");
        logger.info("getElectricityParamInfo subtract33Data {}",dataBCD);
        Map<String,String> map = new HashMap<>();

        //A路电压
        String aVoltage = datastr.substring(0,4);
        aVoltage = dataChange(aVoltage,0);
        logger.info("A路电压：" + aVoltage);
        map.put("aVoltage",aVoltage);
        //B路电压
        String bVoltage = datastr.substring(4,8);
        bVoltage = dataChange(bVoltage,0);
        logger.info("B路电压" + bVoltage);
        map.put("bVoltage",bVoltage);
        //A路电流
        String aCurrent = datastr.substring(8,12);
        aCurrent = dataChange(aCurrent,2);
        logger.info("A路电流" +aCurrent);
        map.put("aCurrent",aCurrent);
        //B路电流
        String bCurrent = datastr.substring(12,16);
        bCurrent = dataChange(bCurrent,2);
        logger.info("B路电流" +bCurrent);
        map.put("bCurrent",bCurrent);
        //总功率
        String sumPower = datastr.substring(16,22);
        sumPower = dataChange(sumPower,4);
        logger.info("总功率:" +sumPower);
        map.put("sumPower",sumPower);
        //A功率
        String aPower = datastr.substring(22,28);
        aPower = dataChange(aPower,4);
        logger.info("A功率:" +aPower);
        map.put("aPower",aPower);
        //B功率
        String bPower = datastr.substring(28,34);
        bPower = dataChange(bPower,4);
        logger.info("B功率:" +bPower);
        map.put("bPower",bPower);
        //总视在功率
        String sumApparentPower = datastr.substring(34,40);
        sumApparentPower = dataChange(sumApparentPower,4);
        logger.info("总视在功率:" +sumApparentPower);
        map.put("sumApparentPower",sumApparentPower);
        //A路视在功率
        String aApparentPower = datastr.substring(40,46);
        aApparentPower = dataChange(aApparentPower,4);
        logger.info("A路视在功率:" +aApparentPower);
        map.put("aApparentPower",aApparentPower);
        //B路视在功率
        String bApparentPower = datastr.substring(46,52);
        bApparentPower = dataChange(bApparentPower,4);
        logger.info("B路视在功率:" +bApparentPower);
        map.put("bApparentPower",bApparentPower);
        //A路功率因素
        String aPowerFactor = datastr.substring(52,56);
        aPowerFactor = dataChange(aPowerFactor,3);
        logger.info("A路功率因素:" +aPowerFactor);
        map.put("aPowerFactor",aPowerFactor);
        //B路功率因素
        String bPowerFactor = datastr.substring(56,60);
        bPowerFactor = dataChange(bPowerFactor,3);
        logger.info("B路功率因素:" +bPowerFactor);
        map.put("bPowerFactor",bPowerFactor);
        //电网频率
        String frequency = datastr.substring(60);
        frequency = dataChange(frequency,2);
        logger.info("电网频率:" +frequency);
        map.put("frequency",frequency);
        redisUtils.set(deviceCode, JSON.toJSONString(map));
    }


    @Override
    public void handleGateWayStatus(String ip, String str,boolean flag) {
        //心跳监控
        LambdaQueryWrapper<SysGateway> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysGateway::getGatewayIp,ip);
        SysGateway vo = new SysGateway();
        vo.setStatus(flag?"1":"0");
        vo.setModifyTime(new Date());
        iotGatewayDao.update(vo,wrapper);
    }

    @Override
    public ResultMsg getSysEwdevicelog(Map<String, Object> map) {
        logger.info("getSysEwdevicelog map{}",map);
        int pageNum = Integer.parseInt((String) map.get("pageNum"));
        int pageSize = Integer.parseInt((String) map.get("pageSize"));
        String ewDeviceId = (String) map.get("ewDeviceId");
        QueryWrapper<SysEwdevicelog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_code",ewDeviceId);
        queryWrapper.orderByDesc("create_time");
        Page<SysEwdevicelog> page = new Page<>(pageNum,pageSize);
        Page<SysEwdevicelog> page1 = sysEwdevicelogDao.selectPage(page, queryWrapper);
        List<SysEwdevicelog> sysEwdevicelogList = page1.getRecords();
        int count = sysEwdevicelogDao.selectCount(queryWrapper);
        int pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        logger.debug("getSysEwdevicelog sysEwdevicelogList{},count{}",sysEwdevicelogList,count);
        map.put("sysEwdevicelogList",sysEwdevicelogList);
        map.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",map);
        return msg;
    }

    /**
     * 电表参数
     * @param id
     * @return
     */
    @Override
    public ResultMsg getSysElectricityInfo(int id) {
        SysEwDevice sysEwDevice = sysEwDeviceDao.selectById(id);
        if (sysEwDevice == null) {
            throw new RuntimeException("不存在该设备");
        }
        String deviceCode = sysEwDevice.getDeviceCode();
        String parameter = redisUtils.get(deviceCode);
        if (!StringUtils.isNotEmpty(parameter)){
            return new ResultMsg(500,"失败",null);
        }
        return new ResultMsg(200,"成功",parameter);
    }

    /**
     * 数据转换
     * @param aVoltage 元数据
     * @param precisionIndex 几位小数
     * @return
     */
    private static String dataChange(String aVoltage,int precisionIndex){
        String dataBCD = ElectricityMeterUtil.hexAddcharacter(aVoltage," ");
        String subtract33Data =  ElectricityMeterUtil.dataAreaSubtract33(dataBCD);
//        logger.info("dataChange {}",subtract33Data);
        String changeAfterStr = ElectricityMeterUtil.addressConvertNo(subtract33Data,false);
        Long changeAfterLong = Long.valueOf(changeAfterStr);
        if(precisionIndex==1){
            return String.valueOf(changeAfterLong*0.1);
        }
        if(precisionIndex==2){
            return String.valueOf(changeAfterLong*0.01);
        }
        if(precisionIndex==3){
            return String.valueOf(changeAfterLong*0.001);
        }
        if(precisionIndex==4){
            return String.valueOf(changeAfterLong*0.0001);
        }
        return String.valueOf(changeAfterLong);
    }
    public static void main(String[] args) {
        String str = "5C355C3548333433C83433C834333333339A363377363355333399383333C37C";
        //A路电压
        String aVoltage = str.substring(0,4);
        aVoltage = dataChange(aVoltage,0);
        System.out.println("A路电压：" + aVoltage);
        //B路电压
        String bVoltage = str.substring(4,8);
        bVoltage = dataChange(bVoltage,0);
        System.out.println("B路电压" + bVoltage);
        //A路电流
        String aCurrent = str.substring(8,12);
        aCurrent = dataChange(aCurrent,3);
        System.out.println("A路电流" +aCurrent);
        //B路电流
        String bCurrent = str.substring(12,16);
        bCurrent = dataChange(bCurrent,3);
        System.out.println("B路电流" +bCurrent);
        //总功率
        String sumPower = str.substring(16,22);
        sumPower = dataChange(sumPower,4);
        System.out.println("总功率:" +sumPower);
        //A功率
        String aPower = str.substring(22,28);
        aPower = dataChange(aPower,4);
        System.out.println("A功率:" +aPower);
        //B功率
        String bPower = str.substring(28,34);
        bPower = dataChange(bPower,4);
        System.out.println("B功率:" +bPower);
        //总视在功率
        String sumApparentPower = str.substring(34,40);
        sumApparentPower = dataChange(sumApparentPower,4);
        System.out.println("总视在功率:" +sumApparentPower);
        //A路视在功率
        String aApparentPower = str.substring(40,46);
        aApparentPower = dataChange(aApparentPower,4);
        System.out.println("A路视在功率:" +aApparentPower);
        //B路视在功率
        String bApparentPower = str.substring(46,52);
        bApparentPower = dataChange(bApparentPower,4);
        System.out.println("B路视在功率:" +bApparentPower);
        //A路功率因素
        String aPowerFactor = str.substring(52,56);
        aPowerFactor = dataChange(aPowerFactor,3);
        System.out.println("A路功率因素:" +aPowerFactor);
        //B路功率因素
        String bPowerFactor = str.substring(56,60);
        bPowerFactor = dataChange(bPowerFactor,3);
        System.out.println("B路功率因素:" +bPowerFactor);
        //电网频率
        String frequency = str.substring(60);
        frequency = dataChange(frequency,2);
        System.out.println("电网频率:" +frequency);
    }
}
